import axios from 'axios'

import store from '@/store'
const token = store.state.user.token

// Create independent axios instance for uploads
const request = axios.create({
    baseURL: 'https://api-hmzs.itheima.net/tj',
    headers: {
        'Authorization': token ? token : ''
    },
    timeout: 100000, // 100 seconds timeout for large files
    withCredentials: true
})

// Add CancelToken to request instance
request.CancelToken = axios.CancelToken

/**
 * 
 * @param {*} file  文件
 * @param {*} onProgress  进度条
 * @param {*} cancelToken 取消请求的token
 * @param  {...any} args 其他参数 {name:'',value:'}
 * @returns 
 */
export function uploadFile(file, onProgress, cancelToken, ...args) {
    const formData = new FormData()
    formData.append('file', file)
    args && args.forEach(arg => formData.append(arg.name, arg.value))

    return request({
        url: '/upload',
        method: 'post',
        data: formData,
        onUploadProgress: (progressEvent) => {
            if (onProgress) {
                const percentCompleted = Math.round(
                    (progressEvent.loaded * 100) / progressEvent.total
                )
                onProgress(percentCompleted)
            }
        },
        cancelToken: cancelToken
    })
}

export function createCancelToken() {
    return request.CancelToken.source()
}


export function isCancel(error) {
    return axios.isCancel(error)
}

export default request
